package com.google.code.task;

import java.util.Map;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;

public class TaskContext {
  static ThreadLocal<Stack<Map<Object, Object>>> threadLocal = new ThreadLocal<Stack<Map<Object, Object>>>() {
    protected synchronized Stack<Map<Object, Object>> initialValue() {
        Stack<Map<Object, Object>> result = new Stack<Map<Object, Object>>();
        return result;
    }
  };

  public static void put(Object key, Object value) {
    Map<Object, Object> map = getLocalMap();
    map.put(key, value);
  }

  public static Object get(Object key) {
    Map<Object, Object> map = getLocalMap();
    return map.get(key);
  }

  public static void startNewContext() {
    getStack().push(new ConcurrentHashMap<Object, Object>());
  }
  
  public static void endCurrentContext() {
    getStack().pop();
  }

  public static Map<Object, Object> getLocalMap() {
    Stack<Map<Object, Object>> stack = getStack();
    return stack.peek();
  }
  
  static Stack<Map<Object, Object>> getStack() {
    return threadLocal.get();
  }

  static void putLocalMap(Map<Object, Object> contextMap) {
    Stack<Map<Object, Object>> stack = getStack();
    stack.push(contextMap);
  }
}
